package com.jzo2o.market.handler;

import com.jzo2o.common.expcetions.CommonException;
import com.jzo2o.common.expcetions.DBException;
import com.jzo2o.market.enums.CouponStatusEnum;
import com.jzo2o.market.model.domain.Activity;
import com.jzo2o.market.model.domain.Coupon;
import com.jzo2o.market.service.IActivityService;
import com.jzo2o.market.service.ICouponService;
import com.jzo2o.redis.sync.SyncManager;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Arrays;

import static com.jzo2o.market.enums.ActivityStatusEnum.*;

@Component
public class XxlJobHandler {

    @Resource
    private SyncManager syncManager;

    @Resource
    private IActivityService activityService;

    @Resource
    private ICouponService couponService;

    /**
     * 活动状态修改，
     * 1.活动进行中状态修改
     * 2.活动已失效状态修改
     * 1分钟一次
     */
    @XxlJob("updateActivityStatus")
    public void updateActivitySatus() {
//更新已经进行中的状态
        boolean result = activityService.lambdaUpdate()
                .eq(Activity::getStatus, NO_DISTRIBUTE.getStatus())
                .le(Activity::getDistributeStartTime, LocalDateTime.now())
                .gt(Activity::getDistributeEndTime, LocalDateTime.now())
                .set(Activity::getStatus, DISTRIBUTING.getStatus())
                .update();
        if (!result) {
            throw new DBException("修改活动状态失败");
        }

        //更新已经结束的
        result = activityService.lambdaUpdate()
                .in(Activity::getStatus, Arrays.asList(DISTRIBUTING.getStatus(), NO_DISTRIBUTE.getStatus()))
                .lt(Activity::getDistributeEndTime, LocalDateTime.now())
                .set(Activity::getStatus, LOSE_EFFICACY.getStatus())
                .update();
        if (!result) {
            throw new DBException("修改活动状态失败");
        }
    }

    /**
     * 已领取优惠券自动过期任务
     */
    @XxlJob("processExpireCoupon")
    public void processExpireCoupon() {
        // 更新优惠券的状态为过期，条件是当前时间大于优惠券的有效时间且优惠券状态为未使用
        boolean result = couponService.lambdaUpdate()
                .lt(Coupon::getValidityTime, LocalDateTime.now())
                .eq(Coupon::getStatus, CouponStatusEnum.NO_USE.getStatus())
                .set(Coupon::getStatus, CouponStatusEnum.INVALID.getStatus())
                .update();
        // 如果更新失败，抛出异常提示设置过期失败
        if (!result) {
            throw new CommonException("优惠券设置过期失败");
        }

    }
}
